﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using NanTongPost.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace rsa_256_
{
    internal class Program
    {
        public class AlipaySignature
        {
            public static string Sign(Dictionary<string, string> parameters, string privateKeyBase64)
            {
                // 1. 参数排序
                var sortedParams = new SortedDictionary<string, string>(parameters);

                // 2. 组装待签名字符串
                string signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));
                Console.WriteLine($"signContent:{signContent}");

                // 3. RSA签名
                try
                {
                    byte[] privateKeyBytes = Convert.FromBase64String(privateKeyBase64);
                    RsaPrivateCrtKeyParameters privateKeyParams = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes);

                    using (var rsa = new RSACryptoServiceProvider())
                    {
                        RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(privateKeyParams);
                        rsa.ImportParameters(rsaParams);

                        byte[] dataToSign = Encoding.UTF8.GetBytes(signContent);
                        byte[] signatureBytes = rsa.SignData(dataToSign, new SHA256CryptoServiceProvider());
                        return Convert.ToBase64String(signatureBytes);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("签名过程中发生错误", ex);
                }
            }
        }


        public static Dictionary<string, string> JsonToDictionary<T>(T json) where T : class,new() 
        {
            var dictionary = new Dictionary<string, string>();

            try
            {
                JObject jObject = JObject.FromObject(json);
                foreach (var pair in jObject)
                {
                    if (pair.Value != null)
                    {
                        dictionary[pair.Key] = pair.Value.ToString();
                    }
                }
            }
            catch (JsonReaderException ex)
            {
                Console.WriteLine($"JSON解析错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }

            return dictionary;
        }

        static void Main(string[] args)
        {
            // 测试代码
            string privateKey = "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDD6g3FbQTM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zPDCcHzaudqwcshyRn4Rt1rzxMw9zgd9fDkp+y3Q55BN2R+cm+stXdvNglzXF1GrSl941RilGRT3bGIzaRY0Fx5ka7ZMa1Lp5Wnpg/Pw4CE8Wy0+uFZcQHmg6Xa5F9ph4uyECgYEApOHdcuwTBtpItuKzPw6whWm7NZm0RFxL3YMID8jBmdmY8tpPYuHTjDppAWf79jdKC/xk4ssjvW7KOU9GHWKkqEYcY9XsgayGan622LEV+aLX7JawkgWk2d7+8Ha+/7CgYFFPfgIj9T9SkYkyCLklVE2id4hyxEibI3wnKMSMBHUCgYEAkwGy+9yR5MttaH+0R1FzprNupC2fv3OdxH8+RfYwL/J+huNHv6dkc1QSZloNeBeFxkvXIsVocJow+3Zz61pZCqbBmAKuPhR+o/oU7NcoUABghU373EBRRue7tjUGywRtTq6bM84hCTKSwCb6fty7U7TTpw1Ee2zn25p5Ej0tmDM=";  // 这里使用空字符串代替实际的私钥

            var model = new ParkingRecord
            {
                CarId = "粤B12345",
                CarType = 1,
                InTime = 20210101120000,
                OutTime = 20210101130000,
                ParkCode = "123456",
                SerialNo = Guid.NewGuid().ToString()
            };

            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(model));
            // 创建测试参数
            var parameters = JsonToDictionary(model);


            //    new Dictionary<string, string>
            //{
            //    { "out_trade_no", "123456" },
            //    { "subject", "测试商品" },
            //    { "total_amount", "88.88" },
            //    { "body", "测试商品描述" }
            //};

            try
            {
                // 签名
                string signature = AlipaySignature.Sign(parameters, privateKey);
                Console.WriteLine("签名结果: " + signature);


            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
            }

            Console.ReadLine();
        }
    }
}